package com.wang.common.exception;

import com.wang.common.common.AResponse;
import com.wang.common.common.ErrorCode;
import com.wang.common.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常捕获
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public AResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("businessException:" + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
    }

    @ExceptionHandler(RuntimeException.class)
    public AResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException:" + e.getMessage(), e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    /**
     * 参数校验异常全局捕获
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AResponse<?> handleValidException(MethodArgumentNotValidException e) {
        Map<String, String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((item) -> map.put(item.getField(), item.getDefaultMessage()));
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, map);
    }
}
